//
//  AddVenueVipViewController.m
//  fitnessmanage
//
//  Created by 众拳科技 on 2017/10/26.
//  Copyright © 2017年 zongquankeji. All rights reserved.
//

#import "AddVenueVipViewController.h"
#import "AddVenueVipView.h"
#import "HZQDatePickerView.h"
#import "MOFSPickerManager.h"
#import "RemarkViewController.h"
#import "SourceAlertView.h"
#import "ZLPhotoPickerViewController.h"
#import "UIImage+ZLPhotoLib.h"
#import "ZLPhotoPickerBrowserPhoto.h"
#import "VipModel.h"
#import "CourseClassAlertView.h"
//#import "AddClassShopStatusViewController.h"

@interface AddVenueVipViewController ()

@property (nonatomic , strong) ZLPhotoPickerBrowserPhoto *photo;

@property(nonatomic,weak)AddVenueVipView *addVenueVipView;

@property(nonatomic,strong)VipModel *vipModel;

@property(nonatomic,weak)CourseClassAlertView *courseClassView;

//数据源
@property(nonatomic,strong)NSMutableArray *dataSource;

//等级字典
@property(nonatomic,strong)NSMutableDictionary *dataDict;

@end

@implementation AddVenueVipViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"添加会员";
    
    self.vipModel = [[VipModel alloc] init];
    
    [self createSubView];
    
    [self loadData];
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(addVipMember)];
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateNormal];
    [rightButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:CSBlackColor,NSFontAttributeName:MidFont} forState:UIControlStateHighlighted];
    
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    [NotificationCenter addObserver:self selector:@selector(loadData) name:@"ReloadShopStatus" object:nil];
    
    if (self.venueVipModel) {
        
        [self setVenueVipModelValue:self.venueVipModel];
    }
}

-(void)createSubView{
    
    AddVenueVipView *addVenueVipView = [[AddVenueVipView alloc] initWithFrame:self.view.frame];
    
    //选择头像
    [addVenueVipView.vipPhotoBtn addTarget:self action:@selector(vipHeadSelect)];
    
    //性别
    [addVenueVipView.sexBtnView.choseBtn addTarget:self action:@selector(sexBtnClick)];
    
    //生日选择
    [addVenueVipView.brithBtnView.choseBtn addTarget:self action:@selector(brithSelect)];
    
    //工作经验选择
    [addVenueVipView.jobExperBtnView.choseBtn addTarget:self action:@selector(jobExperSelect)];
    
    //会员等级
    [addVenueVipView.vipLevelBtnView.choseBtn addTarget:self action:@selector(levelBtnClick)];
    
    //备注
    [addVenueVipView.remarkBtnView.choseBtn addTarget:self action:@selector(remarkBtnClick)];
    
    //来源
    [addVenueVipView.sourceBtnView.choseBtn addTarget:self action:@selector(sourceBtnClick)];
    
    [self.view addSubview:addVenueVipView];
    
    if (self.addVenueVipView) {
        //头像
        [addVenueVipView.vipPhotoBtn sd_setImageWithURL:[Helper imageUrlStringToChinese:self.venueVipModel.Pic imageType:nil] forState:UIControlStateNormal placeholderImage:PlaceHold];
        
        //姓名
        addVenueVipView.nameInputView.titleTF.text = self.venueVipModel.Name;
        
        //性别
        addVenueVipView.sexBtnView.choseLabel.text = [self.venueVipModel.Sex integerValue] == 0?@"男":@"女";
        
        //手机
        addVenueVipView.phoneInputView.titleTF.text = self.venueVipModel.CellPhone;
        
        //生日
        addVenueVipView.brithBtnView.choseLabel.text = self.venueVipModel.Birthday;
        
        //身高
        addVenueVipView.heightInputView.titleTF.text = self.venueVipModel.Height;
        
        //体重
        addVenueVipView.weightInputView.titleTF.text = self.venueVipModel.Weight;
        
        //工作经验
        addVenueVipView.jobExperBtnView.choseLabel.text = self.venueVipModel.Job;
        
        //地址
        addVenueVipView.addrInputView.titleTF.text = self.venueVipModel.Address;
        
        //备注
        addVenueVipView.remarkBtnView.choseLabel.text = self.venueVipModel.Memo;
        
        //会员卡号
        addVenueVipView.vipCardInputView.titleTF.text = self.venueVipModel.CardNum;
        
        //会员等级
        addVenueVipView.vipLevelBtnView.choseLabel.text = self.venueVipModel.Grade;
        
        //紧急联系人
        addVenueVipView.contactInputView.titleTF.text = self.venueVipModel.LxrName;
        
        //工作经验
        addVenueVipView.contactPhoneInputView.titleTF.text = self.venueVipModel.LxrCellPhone;
        
        //来源
        addVenueVipView.sourceBtnView.choseLabel.text = self.venueVipModel.Source;
        
        
    }
    
    self.addVenueVipView = addVenueVipView;
    
    [addVenueVipView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    
}

#pragma mark 加载会员等级数据
-(void)loadData{
    
    [MBProgressHUD showMessage:@"请求中..." toView:self.view];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    BrandModel *brand = [BrandModel brand];
    
    [params setObject:@"会员等级" forKey:@"Type"];
    
//    [params setObject:brand.brandID forKey:@"BrandID"];
    
    [params setObject:[NSString stringWithFormat:@"%d",1] forKey:@"page"];
    
    [params setObject:[NSString stringWithFormat:@"%d",100] forKey:@"rows"];
    
    [HTTPTool GET:Get_SHopStatusList parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  [self.dataSource removeAllObjects];
                  
                  [self.dataDict removeAllObjects];
                  
                  NSMutableArray *resultArray = [responseObject objectForKey:@"rows"];
                  
                  for (NSDictionary *dict in resultArray) {
                      
                      NSString *typeName = [dict objectForKey:@"Name"];
                      
                      [self.dataSource addObject:typeName];
                      
                      [self.dataDict setObject:[dict objectForKey:@"ID"] forKey:typeName];
                  }
              }
              
          }
     
          failure:^(NSError *error){
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}

#pragma mark 等级选择
-(void)levelBtnClick{
    
    [self.view endEditing:YES];
    
    if (self.dataSource.count == 0) {
        
        CourseClassAlertView *courseClassView = [[CourseClassAlertView alloc] init];
        courseClassView.titleLabel.text = @"选择会员等级";
        courseClassView.noticeLabel.text = @"暂无会员等级";
        courseClassView.noticeLabel1.text = @"前往添加会员等级";
        [courseClassView.addBtn setTitle:@"添加会员等级"];
        [courseClassView.addBtn addTarget:self action:@selector(addVipLevel)];
        
        [[UIApplication sharedApplication].keyWindow addSubview:courseClassView];
        
        self.courseClassView = courseClassView;
        
        return;
    }
    
    __weak typeof(self)weakSelf = self;
    
    [[MOFSPickerManager shareManger] showPickerViewWithDataArray:self.dataSource tag:1 title:@"选择会员等级" cancelTitle:@"取消" commitTitle:@"确定" commitBlock:^(NSString *string) {
        
        weakSelf.addVenueVipView.vipLevelBtnView.choseLabel.text = string;
        
        weakSelf.addVenueVipView.vipLevelBtnView.choseLabel.textColor = TFColor;
        
        weakSelf.vipModel.Grade = [NSString stringWithFormat:@"%@",[weakSelf.dataDict objectForKey:string]];
        
    } cancelBlock:^{
        
    }];
}


#pragma mark 选择头像
-(void)vipHeadSelect{
    
    ZLPhotoPickerViewController *pickerVc = [[ZLPhotoPickerViewController alloc] init];
    
    pickerVc.maxCount = 1;
    
    // Jump AssetsVc
    pickerVc.status = PickerViewShowStatusCameraRoll;
    // Recoder Select Assets
    //    pickerVc.selectPickers = self.assets;
    // Filter: PickerPhotoStatusAllVideoAndPhotos, PickerPhotoStatusVideos, PickerPhotoStatusPhotos.
    
    pickerVc.photoStatus = PickerPhotoStatusPhotos;
    // Desc Show Photos, And Suppor Camera
    pickerVc.topShowPhotoPicker = YES;
    
    // CallBack
    __weak typeof(self)weakSelf = self;
    
    pickerVc.callBack = ^(NSArray<ZLPhotoAssets *> *status){
        
        for (ZLPhotoAssets *assets in status) {
            
            ZLPhotoPickerBrowserPhoto *photo = [ZLPhotoPickerBrowserPhoto photoAnyImageObjWith:assets];
            
            photo.asset = assets;
            
            weakSelf.photo = photo;
            
            //拍照
            if ([photo.asset isKindOfClass:[UIImage class]]) {
                
                [weakSelf.addVenueVipView.vipPhotoBtn setImage:(UIImage *)photo.asset forState:UIControlStateNormal];
            }
            else{
                
                [weakSelf.addVenueVipView.vipPhotoBtn setImage:[assets thumbImage] forState:UIControlStateNormal];                
            }
            
            [weakSelf uploadImage];
            
            break;
        }
    };
    
    [pickerVc showPickerVc:self];
}

#pragma mark 上传头像
-(void)uploadImage{
    
    if (!self.photo) {
        
        return;
    }
    
    NSData *imageData;
    
    UIImage *image;
    
    if ([self.photo.asset isKindOfClass:[UIImage class]]) {
        
        image = (UIImage *)self.photo.asset;
    }
    else{
        
        image = [self.photo.asset originImage];
    }
    
    imageData  = UIImageJPEGRepresentation(image,0.1);
    
    [MBProgressHUD showMessage:@"上传中.." toView:self.view];
    
    RAYUploader *upload = [RAYUploader defaultUploader];
    
    [upload uploadWithData:imageData complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        [MBProgressHUD hideHUDForView:self.view];
        
        if (key) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSString *picUrl = [NSString stringWithFormat:@"%@%@",QiNiuBase,key];
                
                self.vipModel.Pic = picUrl;
            });
            
        }
        
    }];
    
}

#pragma mark 生日选择
-(void)brithSelect{
    
    [self.view endEditing:YES];
    
    __weak typeof(self)weakSelf = self;
    
    [[MOFSPickerManager shareManger] showDatePickerWithTag:110 title:@"选择生日" cancelTitle:@"取消" commitTitle:@"确定" datePickerMode:UIDatePickerModeDate commitBlock:^(NSDate *date) {
        
        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];//创建一个日期格式化器
        
        dateFormatter.dateFormat=@"yyyy-MM-dd";//指定转date得日期格式化形式
        
        weakSelf.addVenueVipView.brithBtnView.choseLabel.text = [dateFormatter stringFromDate:date];
        
        weakSelf.addVenueVipView.brithBtnView.choseLabel.textColor = TFColor;
        
        weakSelf.vipModel.Birthday = [dateFormatter stringFromDate:date];
        
    } cancelBlock:^{
        
        
    }];
}

#pragma mark 工作经验选择
-(void)jobExperSelect{
    
    [self.view endEditing:YES];
    
    __weak typeof(self)weakSelf = self;
    NSArray *dataArr = @[@"应届",@"1年",@"2年",@"3年",@"4年",@"5年",@"6年",@"7年",@"8年",@"9年",@"10年以上"];
    
    [[MOFSPickerManager shareManger] showPickerViewWithDataArray:dataArr tag:115 title:@"选择工作经验" cancelTitle:@"取消" commitTitle:@"确定" commitBlock:^(NSString *string) {
        
        weakSelf.addVenueVipView.jobExperBtnView.choseLabel.text = string;
        
        weakSelf.addVenueVipView.jobExperBtnView.choseLabel.textColor = TFColor;
        
        weakSelf.vipModel.Job = string;
        
    } cancelBlock:^{
        
    }];
}
#pragma mark 性别选择
-(void)sexBtnClick{
    
    [self.view endEditing:YES];
    
    __weak typeof(self)weakSelf = self;
    
    [[MOFSPickerManager shareManger] showPickerViewWithDataArray:@[@"男",@"女"] tag:111 title:@"选择性别" cancelTitle:@"取消" commitTitle:@"确定" commitBlock:^(NSString *string) {
        
        weakSelf.addVenueVipView.sexBtnView.choseLabel.text = string;
        
        weakSelf.addVenueVipView.sexBtnView.choseLabel.textColor = TFColor;
        
        weakSelf.vipModel.Sex = [string isEqualToString:@"男"]?@"0":@"1";
        
    } cancelBlock:^{
        
    }];
}

#pragma mark 来源
-(void)sourceBtnClick{
    
    [self.view endEditing:YES];
    
    __weak typeof(self)weakSelf = self;
    
    SourceAlertView *sourceAlertView = [[SourceAlertView alloc] init];
    
    sourceAlertView.commitBlock = ^(NSString *str) {
        
        weakSelf.addVenueVipView.sourceBtnView.choseLabel.text = str;
        
        weakSelf.addVenueVipView.sourceBtnView.choseLabel.textColor = TFColor;
        
        weakSelf.vipModel.Source = str;
    };
    
    [sourceAlertView showWithAnimation];
}

#pragma mark 备注
-(void)remarkBtnClick{
    
    __weak typeof(self)weakSelf = self;
    
    RemarkViewController *remarkVC = [[RemarkViewController alloc] init];
    
    remarkVC.title = @"备注";
    
    remarkVC.placeHold = @"请填写备注";
    
    remarkVC.sendTextBlock = ^(NSString *text) {
        
        weakSelf.addVenueVipView.remarkBtnView.choseLabel.text = text;
        
        weakSelf.addVenueVipView.remarkBtnView.choseLabel.textColor = TFColor;
        
        weakSelf.vipModel.Memo = text;
    };
    
    [self.navigationController pushViewController:remarkVC animated:YES];
}

#pragma mark 添加会员等级

-(void)addVipLevel{
    
    [self.courseClassView removeFromSuperview];
    

 #warning czq
//    AddClassShopStatusViewController *addClassShopStatusVC = [[AddClassShopStatusViewController alloc] init];
//
//    addClassShopStatusVC.titleStr = @"添加会员等级";
//
//    [self.navigationController pushViewController:addClassShopStatusVC animated:YES];
}

-(void)addVipMember{
    
    if (![self checkInput]) {
        
        return;
    }
    
    [MBProgressHUD showMessage:@"请求中..." toView:self.view];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    params = [self.vipModel mj_keyValues];
    
    VenueModel *venue = [VenueModel venue];
    
    [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"ShopID"] forKey:@"ShopID"];
    
    if (self.venueVipModel) {

        [params setObject:self.venueVipModel.ID forKey:@"ID"];
    }
    
    [HTTPTool POSTRaw:Post_MemberOperate parameters:params

              success:^(id responseObject){

                  [MBProgressHUD hideHUDForView:self.view];

                  if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {

                      [MBProgressHUD showText:@"添加成功"];

                      [NotificationCenter postNotificationName:@"ReloadVipMember" object:nil];

                      [self.navigationController popViewControllerAnimated:YES];
                  }

              }

              failure:^(NSError *error){

                  [MBProgressHUD hideHUDForView:self.view];
              }];
}

#pragma mark 检查输入
-(BOOL)checkInput{
    
    //姓名
    NSString *name = self.addVenueVipView.nameInputView.titleTF.text;
    
    //性别
    NSString *sex = self.vipModel.Sex;
    
    //手机
    NSString *phone = self.addVenueVipView.phoneInputView.titleTF.text;
    
    //生日
    NSString *birth = self.vipModel.Birthday;
    
    //身高
    self.vipModel.Name = self.addVenueVipView.heightInputView.titleTF.text;
    
    //体重
    self.vipModel.Weight = self.addVenueVipView.weightInputView.titleTF.text;
    
    //详细地址
    self.vipModel.Address = self.addVenueVipView.addrInputView.titleTF.text;
    
    //详细地址
    self.vipModel.Memo = self.addVenueVipView.remarkBtnView.choseLabel.text;
    
    //会员卡号
    self.vipModel.CardNum = self.addVenueVipView.vipCardInputView.titleTF.text;
    
    //紧急联系人
    self.vipModel.LxrName = self.addVenueVipView.contactInputView.titleTF.text;
    
    //紧急联系人号码
    self.vipModel.LxrCellPhone = self.addVenueVipView.contactPhoneInputView.titleTF.text;
    
    //紧急联系人号码
    self.vipModel.LxrCellPhone = self.addVenueVipView.contactPhoneInputView.titleTF.text;
    
    //等级
    NSString *level = self.vipModel.Grade;
    
    //会员卡号
    NSString *cardNum = self.addVenueVipView.vipCardInputView.titleTF.text;
    
    if ([self.vipModel.Pic isEmptyString] || [self.vipModel.Height isEmptyString]|| [self.vipModel.Weight isEmptyString]|| [self.vipModel.Job isEmptyString]|| [self.vipModel.Height isEmptyString]|| [self.vipModel.Address isEmptyString] || [self.vipModel.CardNum isEmptyString]|| [self.vipModel.LxrName isEmptyString]|| [self.vipModel.LxrCellPhone isEmptyString] || [self.vipModel.Source isEmptyString] || [name isEmptyString] || [sex isEmptyString] || [phone isEmptyString]
        
        ||[birth isEmptyString] || [level isEmptyString]) {
        
        [MBProgressHUD showText:@"请输入此输入项"];
        
        return NO;
    }
    
    self.vipModel.Name = name;
    
    self.vipModel.CellPhone = phone;
    
    //地址
    self.vipModel.Address = self.addVenueVipView.addrInputView.titleTF.text;
    
    //会员卡号
    //self.vipModel.CardNum = cardNum;

    //紧急联系人
    self.vipModel.LxrName = self.addVenueVipView.contactInputView.titleTF.text;
    
    //紧急联系人号码
    self.vipModel.LxrCellPhone = self.addVenueVipView.contactPhoneInputView.titleTF.text;
    
    return YES;
}


-(void)setVenueVipModelValue:(VenueVipModel *)venueVipModel{
    
    self.title =  @"编辑会员";
    
    //头像
    [self.addVenueVipView.vipPhotoBtn sd_setImageWithURL:[NSURL URLWithString:venueVipModel.Pic] forState:UIControlStateNormal];
    self.vipModel.Pic = venueVipModel.Pic;
    
    //姓名
    self.addVenueVipView.nameInputView.titleTF.text = venueVipModel.Name;
    self.vipModel.Name = venueVipModel.Name;
    
    //性别
    self.addVenueVipView.sexBtnView.choseLabel.text = [venueVipModel.Sex intValue] == 0?@"男":@"女";
    self.addVenueVipView.sexBtnView.choseLabel.textColor = TFColor;
    self.vipModel.Sex = venueVipModel.Sex;
    
    //手机
    self.addVenueVipView.phoneInputView.titleTF.text = venueVipModel.CellPhone;
    self.vipModel.CellPhone = venueVipModel.CellPhone;
    
    //生日
    self.vipModel.Birthday = venueVipModel.Birthday;
    self.addVenueVipView.brithBtnView.choseLabel.text = venueVipModel.Birthday;
    self.addVenueVipView.brithBtnView.choseLabel.textColor = TFColor;
    
    //地址
    self.addVenueVipView.addrInputView.titleTF.text = venueVipModel.Address;
    self.vipModel.Address = venueVipModel.Address;
    
    //备注
    self.addVenueVipView.remarkBtnView.choseLabel.text = venueVipModel.Memo;
    self.addVenueVipView.remarkBtnView.choseLabel.textColor = TFColor;
    self.vipModel.Memo = venueVipModel.Memo;
    
    //等级
    self.vipModel.Grade = venueVipModel.Grade;
    self.addVenueVipView.vipLevelBtnView.choseLabel.text = venueVipModel.Grade;
    self.addVenueVipView.vipLevelBtnView.choseLabel.textColor = TFColor;
    
    //紧急联系人
    self.vipModel.LxrName = venueVipModel.LxrName;
    self.addVenueVipView.contactInputView.titleTF.text = venueVipModel.LxrName;
    
    //紧急联系人号码
    self.vipModel.LxrCellPhone = venueVipModel.LxrCellPhone;
    self.addVenueVipView.contactPhoneInputView.titleTF.text = venueVipModel.LxrCellPhone;
    
    //来源
    self.addVenueVipView.sourceBtnView.choseLabel.text = venueVipModel.Source;
    self.addVenueVipView.sourceBtnView.choseLabel.textColor = TFColor;
    self.vipModel.Source = venueVipModel.Source;
}

-(NSMutableArray *)dataSource{
    
    if (!_dataSource) {
        
        _dataSource = [[NSMutableArray alloc] init];
    }
    
    return _dataSource;
    
}

-(NSMutableDictionary *)dataDict{
    
    if (!_dataDict) {
        
        _dataDict = [[NSMutableDictionary alloc] init];
    }
    
    return _dataDict;
}

-(void)dealloc{
    
    [NotificationCenter removeObserver:self];
}

@end
